from flask import Flask

from flask_apscheduler import APScheduler
from werkzeug.exceptions import HTTPException
from infra.config_holder import conf
from infra import logging_handler
from web.blog import blog_ctrl
from web.user import user_ctrl
from infra.error_handler import (
    invalid_request_body,
    http_error,
    internal_error
)

import os

from json import JSONDecodeError

# 配置启动环境变量
os.environ.setdefault('flaskr_env', 'local')
# 初始化flask应用
app = Flask(__name__)
# 定时任务设置
scheduler = APScheduler()
scheduler.init_app(app)
scheduler.start()
# 设置日志
app.logger.addHandler(logging_handler.time_rotating_file_handler(level=conf['log']['level']))
app.logger.setLevel(logging_handler.get_level(conf['log']['level']))
# 注册路由
app.register_blueprint(blog_ctrl)
app.register_blueprint(user_ctrl)
# 注册异常处理
app.register_error_handler(JSONDecodeError, invalid_request_body)
app.register_error_handler(HTTPException, http_error)
app.register_error_handler(Exception, internal_error)
# 生产环境用gunicorn启动，这个是本地自测用的
app.run(host='127.0.0.1', port=8000, debug=True, threaded=True, processes=False, use_reloader=False)
